{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# Geometry\n",
    "\n",
    "gdsfactory provides you with some geometric functions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1",
   "metadata": {},
   "source": [
    "## Boolean\n",
    "There are several common boolean-type operations available in the geometry library.  These include typical boolean operations (and/or/not/xor), offsetting (expanding/shrinking polygons), outlining, and inverting."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "\n",
    "The ``gf.boolean()`` function can perform AND/OR/NOT/XOR operations, and will return a new geometry with the result of that operation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "E = gf.components.ellipse(radii=(10, 5), layer=(1, 0))\n",
    "R = gf.components.rectangle(size=(15, 5), layer=(2, 0))\n",
    "\n",
    "# A new component C is created by performing a boolean operation.\n",
    "# A=E, B=R: E is the shape to be subtracted from, and R is the shape to subtract.\n",
    "# operation=\"not\": This specifies the subtraction operation (A - B).\n",
    "# layer1=(1, 0), layer2=(2, 0): The operation uses the shapes from layer (1, 0) of component E and layer (2, 0) of component R.\n",
    "# layer=(3, 0): The final, resulting shape is placed on a new layer, (3, 0).\n",
    "C = gf.boolean(A=E, B=R, operation=\"not\", layer1=(1, 0), layer2=(2, 0), layer=(3, 0))\n",
    "\n",
    "\n",
    "# Other operations include 'and', 'or', 'xor', or equivalently 'A-B', 'B-A', 'A+B'.\n",
    "\n",
    "# Plot the originals and the result.\n",
    "D = gf.Component()\n",
    "D.add_ref(E)\n",
    "D.add_ref(R)\n",
    "D.add_ref(C).movex(30)\n",
    "D.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "To learn how booleans work you can try all the different operations `not`, `and`, `or`, `xor`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "operation = \"not\" # This is subtraction (A - B). It keeps the parts of shape A that do not overlap with shape B.\n",
    "operation = \"and\" # This is intersection (A ∩ B). It keeps only the parts where shape A and shape B overlap.\n",
    "operation = \"or\"  # This is union (A ∪ B). It combines shape A and shape B into a single, merged shape.\n",
    "operation = \"xor\" # This is exclusive OR (symmetric difference). It keeps the parts of shape A and shape B that do not overlap.\n",
    "\n",
    "r1 = (8, 8)\n",
    "r2 = (11, 4)\n",
    "r1 = (80, 80)\n",
    "r2 = (110, 40)\n",
    "\n",
    "angle_resolution = 0.1\n",
    "\n",
    "c1 = gf.components.ellipse(radii=r1, layer=(1, 0), angle_resolution=angle_resolution)\n",
    "c2 = gf.components.ellipse(radii=r2, layer=(1, 0), angle_resolution=angle_resolution)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": [
    "c4 = gf.boolean(c1, c2, operation=operation, layer=(1, 0))\n",
    "c4.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7",
   "metadata": {},
   "source": [
    "## Flatten\n",
    "\n",
    "Hierarchical GDS uses references to optimize memory usage, but there are times when you may want to merge all polygons. In such cases, you can flatten the GDS to absorb all the references."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "c = gf.Component()\n",
    "e = c << gf.components.ellipse(\n",
    "    radii=(10, 5), layer=(1, 0)\n",
    ")  # Ellipse. equivalent to c.add_ref(gf.components.ellipse(radii=(10, 5), layer=(1, 0)).\n",
    "r = c << gf.components.rectangle(\n",
    "    size=(15, 5), layer=(2, 0)\n",
    ")  # Rectangle. equivalent to c.add_ref(gf.components.rectangle(size=(15, 5), layer=(2, 0)).\n",
    "print(len(c.insts))  # 2 component instances.\n",
    "\n",
    "# This command flattens the component c, removing all levels of hierarchy.\n",
    "# It replaces all instances (references) of sub-components with copies of their raw geometric shapes.\n",
    "c.flatten()\n",
    "print(len(c.insts))  # 0 in the flattened component.\n",
    "c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9",
   "metadata": {},
   "source": [
    "## Fix min space violations\n",
    "\n",
    "You can use `fix_spacing` to fix min space violations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.components.coupler_ring(cross_section='rib')\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = c.copy()\n",
    "c.fix_spacing(layer=(3,0), min_space=1)\n",
    "c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "## Fix min width violations\n",
    "\n",
    "Some PDKs have minimum width rules, where a geometry is too narrow and needs to be widened. GDSFactory provides a function to fix this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.c.taper(width1=10, width2=1, length=5)\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.c.taper(width1=10, width2=1, length=5).copy()\n",
    "c.fix_width(layer=(1, 0), min_width=1)\n",
    "c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15",
   "metadata": {},
   "source": [
    "## Offset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "from gdsfactory.generic_tech import LAYER\n",
    "\n",
    "c = gf.components.coupler_ring()\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17",
   "metadata": {},
   "outputs": [],
   "source": [
    "r = c.get_region(LAYER.WG)\n",
    "r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18",
   "metadata": {},
   "outputs": [],
   "source": [
    "c2 = c.copy()\n",
    "r = r.sized(2000)  # Note that the region is sized in DB units (1nm).\n",
    "c2.add_polygon(r, layer=LAYER.SLAB90)\n",
    "c2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19",
   "metadata": {},
   "source": [
    "To avoid acute angles you can run over / under (dilation+erosion)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20",
   "metadata": {},
   "outputs": [],
   "source": [
    "c2 = c.copy()\n",
    "\n",
    "d = 800  # DB units\n",
    "r = r.sized(+d + 2000)\n",
    "r = r.sized(-d)\n",
    "c2.add_polygon(r, layer=LAYER.SLAB90)\n",
    "c2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21",
   "metadata": {},
   "source": [
    "You can also apply it to a component directly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "core = gf.components.coupler_ring()\n",
    "\n",
    "clad = core.copy()\n",
    "clad.offset(layer=\"WG\", distance=1)\n",
    "clad.remap_layers({\"WG\": \"SLAB90\"})\n",
    "\n",
    "c.add_ref(core)\n",
    "c.add_ref(clad)\n",
    "\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.over_under(layer=\"SLAB90\", distance=0.2)\n",
    "c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "24",
   "metadata": {},
   "source": [
    "## Outline\n",
    "\n",
    "Notice that all operations with regions are in database units, where 1DBU is usually 1nm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25",
   "metadata": {},
   "outputs": [],
   "source": [
    "c2 = gf.Component()\n",
    "\n",
    "d = 800\n",
    "r = c.get_region(layer=LAYER.WG)\n",
    "r_sized = r.sized(+2000)\n",
    "\n",
    "r_outline = r_sized - r\n",
    "c2.add_polygon(r_outline, layer=LAYER.SLAB90)\n",
    "c2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26",
   "metadata": {},
   "source": [
    "## Round corners"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.components.triangle()\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28",
   "metadata": {},
   "outputs": [],
   "source": [
    "c2 = gf.Component()\n",
    "\n",
    "rinner = 1000  # \tThe circle radius of inner corners (in database units).\n",
    "router = 1000  # \tThe circle radius of outer corners (in database units).\n",
    "n = 300  # \tThe number of points per full circle.\n",
    "\n",
    "# Round corners for one layer only.\n",
    "for p in c.get_polygons()[LAYER.WG]:\n",
    "    p_round = p.round_corners(rinner, router, n)\n",
    "    c2.add_polygon(p_round, layer=LAYER.WG)\n",
    "\n",
    "c2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "t = c << gf.components.triangle(x=10, y=20, layer=\"WG\")\n",
    "t = c << gf.components.triangle(x=20, y=40, layer=\"SLAB90\")\n",
    "\n",
    "c2 = gf.Component()\n",
    "rinner = 1000 \n",
    "router = 1000 \n",
    "n = 300 \n",
    "\n",
    "# Round corners for all layers.\n",
    "for layer, polygons in c.get_polygons().items():\n",
    "    for p in polygons:\n",
    "        p_round = p.round_corners(rinner, router, n)\n",
    "        c2.add_polygon(p_round, layer=layer)\n",
    "\n",
    "c2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30",
   "metadata": {},
   "source": [
    "## Union"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "# This code creates a component containing six overlapping ellipses,\n",
    "# each on a different layer and each rotated by an incrementally larger angle, creating a flower-like pattern.\n",
    "c = gf.Component()\n",
    "e0 = c << gf.components.ellipse(layer=(1, 0))\n",
    "e1 = c << gf.components.ellipse(layer=(2, 0))\n",
    "e2 = c << gf.components.ellipse(layer=(3, 0))\n",
    "e3 = c << gf.components.ellipse(layer=(4, 0))\n",
    "e4 = c << gf.components.ellipse(layer=(5, 0))\n",
    "e5 = c << gf.components.ellipse(layer=(6, 0))\n",
    "\n",
    "e1.rotate(15 * 1)\n",
    "e2.rotate(15 * 2)\n",
    "e3.rotate(15 * 3)\n",
    "e4.rotate(15 * 4)\n",
    "e5.rotate(15 * 5)\n",
    "\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32",
   "metadata": {},
   "outputs": [],
   "source": [
    "r = gf.Region()\n",
    "\n",
    "for layer in c.layers:\n",
    "    r = r + c.get_region(layer)\n",
    "\n",
    "c2 = gf.Component()\n",
    "c2.add_polygon(r, layer=(1, 0))\n",
    "c2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33",
   "metadata": {},
   "source": [
    "## Smooth\n",
    "\n",
    "You can also simplify polygons."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.components.circle()\n",
    "c2 = gf.Component()\n",
    "region = c.get_region(layer=LAYER.WG, smooth=1)\n",
    "c2.add_polygon(region, layer=LAYER.WG)\n",
    "c2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35",
   "metadata": {},
   "source": [
    "As well as easily do boolean operations with regions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "36",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.components.circle()\n",
    "c2 = gf.Component()\n",
    "region = c.get_region(layer=LAYER.WG, smooth=1)\n",
    "region2 = region.sized(100)\n",
    "region3 = region2 - region\n",
    "\n",
    "c2.add_polygon(region3, layer=LAYER.WG)\n",
    "c2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37",
   "metadata": {},
   "source": [
    "## Importing GDS files"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38",
   "metadata": {},
   "source": [
    "`gf.import_gds()` allows you to easily import external GDSII files.  It imports a single cell from the external GDS file and converts it into a gdsfactory component."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39",
   "metadata": {},
   "outputs": [],
   "source": [
    "D = gf.components.ellipse()\n",
    "D.write_gds(\"myoutput.gds\")\n",
    "D2 = gf.import_gds(gdspath=\"myoutput.gds\")\n",
    "D2.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40",
   "metadata": {},
   "source": [
    "## Copying and extracting geometry"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41",
   "metadata": {},
   "outputs": [],
   "source": [
    "E = gf.Component()\n",
    "E.add_ref(gf.components.ellipse(layer=(1, 0)))\n",
    "D = E.extract(layers=[(1, 0)])\n",
    "D.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "X = gf.components.ellipse(layer=(2, 0))\n",
    "c = X.copy()\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.c.straight()\n",
    "c = c.copy()\n",
    "\n",
    " # Type: ignore to tell the static type checker, like Mypy or Pylance, to deliberately ignore a potential type error on that specific line of code.\n",
    " # In this case, the copy_layers method might be type-hinted to expect a dictionary with a more specific key type,\n",
    " # such as gf.typings.Layer, instead of a simple string like \"WG\". This might potentially flag as error or mismatch.\n",
    "c.copy_layers(layer_map=dict(WG=(2, 0)), recursive=False)\n",
    "c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44",
   "metadata": {},
   "source": [
    "## Import Images into GDS\n",
    "\n",
    "You can import your logo into GDS using the conversion from numpy arrays."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "from gdsfactory.config import PATH\n",
    "from gdsfactory.read.from_np import from_image\n",
    "\n",
    "c = from_image(\n",
    "    PATH.module / \"samples\" / \"images\" / \"logo.png\", nm_per_pixel=500, invert=False\n",
    ")\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = from_image(\n",
    "    PATH.module / \"samples\" / \"images\" / \"logo.png\", nm_per_pixel=500, invert=True\n",
    ")\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47",
   "metadata": {},
   "source": [
    "## Dummy Fill / Tiling\n",
    "\n",
    "To keep constant density in some layers you can add dummy fill shapes.\n",
    "\n",
    "For big layouts you should use a tiling processor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "c = gf.Component()\n",
    "c << gf.components.die_with_pads()\n",
    "fill = gf.c.rectangle(layer=\"M3\")\n",
    "c.fill(\n",
    "    fill_cell=fill,\n",
    "    fill_layers=[(\"FLOORPLAN\", -100)],\n",
    "    exclude_layers=[\n",
    "        ((1, 0), 100),\n",
    "        (\"M3\", 100)\n",
    "        ],\n",
    "    x_space=1,\n",
    "    y_space=1,\n",
    ")\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49",
   "metadata": {},
   "outputs": [],
   "source": [
    "@gf.cell\n",
    "def fill_cell():\n",
    "    c = gf.Component()\n",
    "    c << gf.c.rectangle(layer=(3,0), size=(1,1))\n",
    "    c << gf.c.rectangle(layer=(2,0), size=(1,1))\n",
    "    return c\n",
    "\n",
    "c = gf.Component()\n",
    "r = c << gf.c.ellipse(layer=(1,0), radii=(100,50))\n",
    "t = c << gf.c.triangle(layer=(2,0))\n",
    "\n",
    "c.fill(fill_cell=fill_cell(),\n",
    "    fill_layers=[(\"WG\", -1)],\n",
    "    exclude_layers=[((2,0), 10)],\n",
    "    x_space=1,\n",
    "    y_space=1,\n",
    ")\n",
    "c"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "custom_cell_magics": "kql"
  },
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
